package com.mingyuan;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class HelloTransformer implements ClassFileTransformer {

    public final String TEST_CLASS_NAME = "com.mingyuan.showCode.ApiTest";

    public final String METHOD_NAME = "queryUserInfo";


    public byte[] transform(ClassLoader loader,
                            String className,
                            Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain,
                            byte[] classfileBuffer) throws IllegalClassFormatException {

        String finalClassName = className.replace("/", ".");

        if (TEST_CLASS_NAME.equals(finalClassName)) {
            System.out.println(finalClassName+" name 匹配上了 !");

            CtClass ctClass;

            try {
                ctClass = ClassPool.getDefault().get(finalClassName);
                System.out.println(ctClass+" is OK !");
                CtMethod ctMethod = ctClass.getDeclaredMethod(METHOD_NAME);
                System.out.println(ctMethod+" is OK !");
                ctMethod.insertBefore("System.out.println(\"字节码添加成功，打印日志 !\");");
                return ctClass.toBytecode();
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }

        return null;
    }
}
